package cn.net.yugu.doraemon.springweb.util;

import cn.net.yugu.doraemon.springweb.enums.SignAlgorithmType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author wanghongli
 * @date 2023/3/21 13:10
 * @description SignUtil
 **/
@Slf4j
public class SignUtil {
    public static String sign(Map<String, String> param, String salt, SignAlgorithmType algorithmType) {
        List<String> keys = null;
        StringBuilder toSign = new StringBuilder();
        if (StringUtils.isNotBlank(param.get("signType")) && NumberUtils.isNumber(param.get("signType")) && param.get("signType").length()>2){
            keys = param.entrySet().stream()
                    .sorted(Map.Entry.comparingByValue())
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());
            for (String key : keys) {
                String value = param.get(key);
                if (null != value && !"".equals(value) && !"sign".equals(key)
                        && !"key".equals(key)) {
                    toSign.append(value).append("&");
                }
            }
        }else{
            keys = new ArrayList<>(param.keySet());
            Collections.sort(keys);
            for (String key : keys) {
                String value = param.get(key);
                if (null != value && !"".equals(value) && !"sign".equals(key)
                        && !"key".equals(key)) {
                    toSign.append(key).append("=").append(value).append("&");
                }
            }
        }

        if (StringUtils.isNotEmpty(salt)) {
            toSign.append("key=").append(salt);
        } else if (toSign.length()>0){
            toSign.setLength(toSign.length() - 1);
        }
        if (log.isDebugEnabled()) {
            log.debug("sign, str:{}", toSign);
        }
        switch (algorithmType) {
            case MD5:
                return DigestUtils.md5Hex(toSign.toString().getBytes(StandardCharsets.UTF_8));
            case SHA1:
                return DigestUtils.sha1Hex(toSign.toString().getBytes(StandardCharsets.UTF_8));
            default:
                throw new RuntimeException("unSupport sign algorithm");
        }
    }
}
